import { Controller, Get, Post, Body, Param, UseGuards, Request, Put } from '@nestjs/common';
import { ChatService } from './chat.service';
import { CreateMessageDto } from './dto/create-message.dto';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';

@Controller('chat')
@UseGuards(JwtAuthGuard)
export class ChatController {
  constructor(private readonly chatService: ChatService) {}

  @Post('message')
  async createMessage(@Request() req, @Body() createMessageDto: CreateMessageDto) {
    const userId = req.user.userId;
    const message = await this.chatService.create(userId, createMessageDto);
    return {
      message: '消息发送成功',
      data: message,
    };
  }

  @Post('ai-message')
  async createAIMessage(@Request() req, @Body() body: { content: string }) {
    const userId = req.user.userId;
    const result = await this.chatService.createAIMessage(userId, body.content);
    
    return {
      message: 'AI消息发送成功',
      data: result,
    };
  }

  @Get('conversations')
  async getRecentChats(@Request() req) {
    const userId = req.user.userId;
    const chats = await this.chatService.getRecentChats(userId);
    return {
      message: '获取最近聊天成功',
      data: chats,
    };
  }

  @Get('conversation/:id')
  async getConversation(@Request() req, @Param('id') id: string) {
    const userId = req.user.userId;
    
    // 处理AI助手的特殊情况
    if (id === 'ai-assistant') {
      const messages = await this.chatService.findAIConversation(userId);
      return {
        message: '获取AI助手对话成功',
        data: messages,
      };
    }
    
    const otherUserId = parseInt(id, 10);
    const messages = await this.chatService.findConversation(userId, otherUserId);
    return {
      message: '获取对话成功',
      data: messages,
    };
  }

  @Put('message/:id/read')
  async markAsRead(@Param('id') id: string) {
    const messageId = parseInt(id, 10);
    const message = await this.chatService.markAsRead(messageId);
    return {
      message: '标记消息为已读成功',
      data: message,
    };
  }

  @Get('unread-count')
  async getUnreadCount(@Request() req) {
    const userId = req.user.userId;
    const count = await this.chatService.getUnreadCount(userId);
    return {
      message: '获取未读消息数量成功',
      data: { count },
    };
  }

  // 模拟AI回复
  private getAIResponse(): string {
    const responses = [
      "您好！很高兴能和您聊天，有什么我可以帮助您的吗？",
      "今天天气真不错，适合出去散步。您最近有什么有趣的活动吗？",
      "我很乐意听您分享生活中的故事和经历。",
      "如果您有任何问题，无论是关于健康、爱好还是日常生活，都可以随时问我。",
      "您的家人最近好吗？有没有什么新鲜事？",
      "我注意到您似乎对这个话题很感兴趣，您想了解更多相关信息吗？",
      "这是个很好的问题！让我来为您解答。",
      "您的想法非常有创意！能分享更多细节吗？",
      "我理解您的感受，有时候生活确实会有些挑战。",
      "如果您感到孤单，随时可以来找我聊天，我一直都在这里。",
      "您有什么喜欢的书籍或电影吗？我很想听听您的推荐。",
      "您的经历真的很精彩！能告诉我更多吗？",
      "我很高兴能成为您的聊天伙伴，希望我的陪伴能给您带来一些快乐。",
      "您有什么想要分享的新闻或故事吗？",
      "如果您想学习新东西，我可以帮您找一些适合的资源。",
    ];
    
    const randomIndex = Math.floor(Math.random() * responses.length);
    return responses[randomIndex];
  }
}